#include "cjsonobject.h"
#include "cjsonerror.h"

CJsonObject::CJsonObject() :
  CJsonValue(JV_OBJECT)
{
}

CJsonObject::~CJsonObject()
{
  Clear();
}

jstring CJsonObject::ToString()
{
    jstring result = J("{");
    for (unsigned i = 0; i < pares.size(); i++)
    {
        if (i)
        {
            result += J(",");
        }
        result += pares[i]->ToString();
    }
    result += J("}");
    return result;
}

void CJsonObject::AddPare(CJsonPare *pare)
{
    if (!pare)
    {
        throw CJsonError(INVALID_PARAM);
    }
    pares.push_back(pare);
}

CJsonValue * CJsonObject::operator [] (jstring & name) const
{
  for (std::size_t i = 0; i < pares.size(); i++)
  {
    if (pares[i]->CompareName(name))
    {
      return pares[i]->GetValue();
    }
  }
  return NULL;
}

bool CJsonObject::Empty() const
{
  return pares.empty();
}

CJsonPare * CJsonObject::Pop()
{
  CJsonPare *pare = pares.front();
  pares.erase(pares.begin());
  return pare;
}

void CJsonObject::Clear()
{
  while (!pares.empty())
  {
    if (pares.back())
    {
      delete pares.back();
    }
    pares.pop_back();
  }
}

